<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检验任务ID" prop="inspectionTaskId">
        <el-input
          v-model="queryParams.inspectionTaskId"
          placeholder="请输入检验任务ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="缺陷类型" prop="defectType">
        <el-select v-model="queryParams.defectType" placeholder="请选择缺陷类型" clearable>
          <el-option label="外观缺陷" value="外观缺陷" />
          <el-option label="功能缺陷" value="功能缺陷" />
          <el-option label="结构缺陷" value="结构缺陷" />
          <el-option label="性能缺陷" value="性能缺陷" />
          <el-option label="其他缺陷" value="其他缺陷" />
        </el-select>
      </el-form-item>
      <el-form-item label="严重程度" prop="severity">
        <el-select v-model="queryParams.severity" placeholder="请选择严重程度" clearable>
          <el-option label="致命" value="致命" />
          <el-option label="严重" value="严重" />
          <el-option label="一般" value="一般" />
          <el-option label="轻微" value="轻微" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          @click="handleAdd"
          v-hasPermi="['qep:defect-record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qep:defect-record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qep:defect-record:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="defectRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50"/>
      <el-table-column label="缺陷编号" align="center" prop="id" />
      <el-table-column label="检验任务ID" align="center" prop="inspectionTaskId" />
      <el-table-column label="缺陷类型" align="center" prop="defectType" />
      <el-table-column label="严重程度" align="center" prop="severity">
        <template #default="scope">
          <el-tag :type="scope.row.severity === '致命' ? 'danger' : 
                        scope.row.severity === '严重' ? 'warning' :
                        scope.row.severity === '一般' ? 'info' : 'success'">
            {{ scope.row.severity }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发现时间" align="center" prop="createTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="缺陷位置" align="center" prop="location" :show-overflow-tooltip="true" />
      <el-table-column label="缺陷图片" align="center" width="100">
        <template #default="scope">
          <el-image 
            v-if="scope.row.imageUrl" 
            :src="getImageUrl(scope.row.imageUrl)" 
            style="width: 60px; height: 60px" 
            :preview-src-list="[getImageUrl(scope.row.imageUrl)]"
            preview-teleported
          ></el-image>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="primary"
            link
            :icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['qep:defect-record:query']"
          >查看</el-button>
          <el-button
            type="primary"
            link
            :icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qep:defect-record:edit']"
          >修改</el-button>
          <el-button
            type="primary"
            link
            :icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qep:defect-record:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改缺陷记录对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="检验任务ID" prop="inspectionTaskId">
          <el-input v-model="form.inspectionTaskId" placeholder="请输入检验任务ID" />
        </el-form-item>
        <el-form-item label="缺陷类型" prop="defectType">
          <el-select v-model="form.defectType" placeholder="请选择缺陷类型">
            <el-option label="外观缺陷" value="外观缺陷" />
            <el-option label="功能缺陷" value="功能缺陷" />
            <el-option label="结构缺陷" value="结构缺陷" />
            <el-option label="性能缺陷" value="性能缺陷" />
            <el-option label="其他缺陷" value="其他缺陷" />
          </el-select>
        </el-form-item>
        <el-form-item label="严重程度" prop="severity">
          <el-select v-model="form.severity" placeholder="请选择严重程度">
            <el-option label="致命" value="致命" />
            <el-option label="严重" value="严重" />
            <el-option label="一般" value="一般" />
            <el-option label="轻微" value="轻微" />
          </el-select>
        </el-form-item>
        <el-form-item label="缺陷位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入缺陷位置" />
        </el-form-item>
        <el-form-item label="缺陷图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listDefectRecord, getDefectRecord, addDefectRecord, updateDefectRecord, delDefectRecord } from "@/api/qep/defectRecord";
import { Search, Refresh, Plus, Edit, Delete, View } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import ImageUpload from "@/components/ImageUpload";

export default {
  name: "DefectRecord",
  components: {
    ImageUpload
  },
  data() {
    return {
      // 图标
      Search,
      Refresh,
      Plus,
      Edit,
      Delete,
      View,
      // 遮罩层
      loading: true,
      // 提交按钮加载状态
      submitLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 缺陷记录表格数据
      defectRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 基础URL
      baseUrl: import.meta.env.VITE_APP_BASE_API,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inspectionTaskId: null,
        defectType: null,
        severity: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        inspectionTaskId: [
          { required: true, message: "检验任务ID不能为空", trigger: "blur" }
        ],
        defectType: [
          { required: true, message: "缺陷类型不能为空", trigger: "change" }
        ],
        severity: [
          { required: true, message: "严重程度不能为空", trigger: "change" }
        ],
        location: [
          { required: true, message: "缺陷位置不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 获取完整图片URL */
    getImageUrl(url) {
      if (!url) return "";
      
      // 如果已经是完整URL（以http或https开头）
      if (url.startsWith("http://") || url.startsWith("https://")) {
        return url;
      }
      
      // 如果是以/开头的相对路径
      if (url.startsWith("/")) {
        return this.baseUrl + url;
      }
      
      // 如果是不以/开头的相对路径
      return this.baseUrl + "/" + url;
    },
    /** 查询缺陷记录列表 */
    getList() {
      this.loading = true;
      listDefectRecord(this.queryParams).then(response => {
        this.defectRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error("获取缺陷记录失败", error);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        inspectionTaskId: null,
        defectType: null,
        severity: null,
        location: null,
        imageUrl: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加缺陷记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getDefectRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改缺陷记录";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id;
      getDefectRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看缺陷记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.submitLoading = true;
          if (this.form.id != null) {
            updateDefectRecord(this.form).then(response => {
              ElMessage.success("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.submitLoading = false;
            });
          } else {
            addDefectRecord(this.form).then(response => {
              ElMessage.success("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.submitLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      ElMessageBox.confirm('是否确认删除缺陷记录编号为"' + ids + '"的数据项？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return delDefectRecord(ids);
      }).then(() => {
        this.getList();
        ElMessage.success("删除成功");
      }).catch(() => {
        this.loading = false;
      });
    }
  }
};
</script> 